/*
 * @filename WebUtils.java
 * @author barry
 * @version 0.0.1
 * @date 2019年12月9日
 */
package com.bnzj.core.webmvc.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bnzj.core.util.FbConstant;
import com.bnzj.core.web.util.WebUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author barry
 * @date 2019-12-09
 */
@Slf4j
public class WebMvcUtils {
    
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }
    
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static String getIpAddress() {
        return getIpAddress(getRequest());
    }
    
    public static String getCurrentView() {
        String path = getRequest().getRequestURI();
        path = path.replaceFirst("/", "");
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        return path;
    }
    
    public static Pageable initPage() {
        return initPage((Sort)null);
    }
    
    public static Pageable initPage(Sort sort) {
        return initPage(getRequest(), sort);
    }
    
    public static Pageable initPage(HttpServletRequest httpRequest) {
        return initPage(httpRequest, null);
    }
    
    public static Pageable initPage(HttpServletRequest httpRequest, Sort sort) {
        return WebUtils.initPage(httpRequest.getParameter("limit"), httpRequest.getParameter("offset"), sort);
    }
    
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * 编码文件名称
     * @param fileName
     * @return
     */
    public static String encodeFileName(String userAgent, String fileName) {
        String newName = fileName;
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("like Gecko")) {
                newName = URLEncoder.encode(fileName, FbConstant.GLOBAL_ENCODE);
            } else {
                newName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
        }
        return newName;
    }


    /**
     * @Description 将分页查询传入数据封装成Pageable对象
     * @param page: 第几页
     * @param size: 多少条一页
     * @param orders: 排序规则集合(["name:0", "date:1"] 表示先按名字增序排列再按日期降序排列)
     * @return: org.springframework.data.domain.Pageable 分页对象
     * @Author
     * @Date 2020/2/18
     **/
    public static Pageable parseOrderProperties(int page, int size, List<String> orders){
        List<Sort.Order> sortOrders = Collections.emptyList();
        if(orders != null && !orders.isEmpty()){
            sortOrders = orders.stream().filter(
                        //筛选符合规则的排序参数
                        order->!org.springframework.util.StringUtils.isEmpty(order) &&
                        (order.split(":").length==2 && ("0".equals(order.split(":")[1]) || "1".equals(order.split(":")[1])))
                    )
                    .map(order->{
                        String[] orderItem = order.split(":");
                        String propertyName = orderItem[0];
                        int orderDirection = Integer.parseInt(orderItem[1]);
                        Sort.Order sortOrder = new Sort.Order(Sort.Direction.values()[orderDirection], propertyName);
                        return sortOrder;
                    }).collect(Collectors.toList());

        }
        Sort sort = sortOrders.isEmpty() ? Sort.unsorted() : Sort.by(sortOrders);
        return PageRequest.of(page, size, sort);
    }
}
